#include "http.hpp"
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define WWWROOT "./wwwroot"
std::string RequestStr(const HttpRequest &req)
{
    std::stringstream ss;
    ss << req._method << " " << req._uri << " " << req._version << "\r\n";
    for (auto &it : req._params)
    {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for (auto &it : req._headers)
    {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}
void Hello(const HttpRequest &req, HttpResponse *rsp)
{

    rsp->SetBody(RequestStr(req) + "hello world", "text/plain");
}
void Login(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetBody(RequestStr(req), "text/plain");
}
void PutFile(const HttpRequest &req, HttpResponse *rsp)
{
    // DBG_LOG("开始写文件");
    std::string pathname = WWWROOT + req._uri;

    if (Util::WriteFile(pathname, req._body))
    {
        // DBG_LOG("文件写入成功");
        //  文件写入成功
        rsp->SetBody("File uploaded successfully", "text/plain");
        rsp->_status = 200; // 或者 201 Created
    }
    else
    {
        DBG_LOG("文件写入失败");
        // 文件写入失败
        rsp->SetBody("File upload failed", "text/plain");
        rsp->_status = 500;
    }
}
void DelFile(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetBody(RequestStr(req), "text/plain");
}

int main()
{
    daemon(1, 1);
    HttpServe server(8089, 30);

    server.SetThreadCount(8);
    server.SeTBaseDir(WWWROOT); // 设置静态资源根目录，告诉服务器有静态资源请求到来，需要到哪里去找资源文件
    server.AddGetHandler("/hello", Hello);
    server.AddPostHandler("/login", Login);
    server.AddPutHandler("/1234.txt", PutFile);
    server.AddDeleteHandler("/1234.txt", DelFile);
    server.Start();
    return 0;
}
